package com.itany.corejava.code12_线程.zuoye;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年07月30日16:51
 */

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 创建一个类，实现Runnable接口
 * 在该类中有一个数组，如:int[] arr={10,4,20,50,100,200,500,800,3,80,345}
 * 定义两个线程，借助于上面创建的类
 * 在控制台输每隔一秒输出上面数组中的任意一个值，不允许重复，输出完就结束
 */
public class Test01 {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread t1=new Thread(myThread,"线程一");
        Thread t2=new Thread(myThread,"线程二");
        t1.start();
        t2.start();
    }
}

class MyThread implements Runnable {
    int[] arr = {10, 4, 20, 50, 100, 200, 500, 800, 3, 80, 345};
    List<Integer> list = new ArrayList<>();

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                Random random = new Random();
                int i = random.nextInt(arr.length);//[0-10]
                if (!list.contains(arr[i])) {
                    list.add(arr[i]);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "抽出了一个数字:" + arr[i]);
                }

            }
            if (list.size() == arr.length) {
                break;
            }


        }
    }
}

